extends Control

onready var price_inputs = $VBoxContainer/Panel2/price_inputs
var close_on_select = true
signal selected(value)
var item = null
var frames_visible = 0

func _ready():
	for i in price_inputs.get_child_count():
		var current = price_inputs.get_child(i)
		if i > 0: current.previous = price_inputs.get_child(i-1)
		if i < price_inputs.get_child_count()-1: current.next = price_inputs.get_child(i+1)
		current.connect("changed", self, "on_value_changed")

func open(shopper, item_arg, rehaggle=false):
	self.item = item_arg
	$VBoxContainer/Panel/HBoxContainer/item_name.text = item.definition.full_name()
	if not rehaggle:
		set_base_string(item.definition.base_value)
		$VBoxContainer/Panel/HBoxContainer/item_icon.texture = item.definition.icon()
	
		set_value(item.definition.base_value)
		
	var grabbed_focus = false
	for c in price_inputs.get_children():
		if c.value != 0: 
			c.grab_focus()
	if not grabbed_focus:
		var inputs = price_inputs.get_children()
		inputs.invert()
		inputs[0].grab_focus()
	self.visible = true
	$AnimationPlayer.play("open")
	frames_visible = 0
	
func _process(delta):
	if not self.visible: return
	frames_visible += 1
	if frames_visible > 2 && Input.is_action_just_pressed("ui_accept"):
		close()
		
func get_value():
	var i = 0
	var inputs = price_inputs.get_children()
	var value = 0
	inputs.invert()
	for c in inputs:
		value += c.value * (pow(10,i))
		i += 1
	return value
	
func set_value(v:int):
	var i = 0
	var inputs = price_inputs.get_children()
	inputs.invert()
	for c in inputs:
		var bigger = int(pow(100,i))
		var lower = int(pow(10, i))
		var digit = int((v - int(v / bigger) * bigger  - (v % lower)) / lower)
		c.set_value(digit, false)
		i += 1
		
func close():
	print("value ", get_value())
	emit_signal("selected", get_value())
	self.visible = false
	
func set_base_string(value:int):
	var base = item.definition.base_value
	var percent = int((float(value) / (max(float(base), 1.0))) * 100.0)
	$VBoxContainer/Panel3/base_price.text = "base " + str(base) + " (" + str(percent) +  "%)"

func on_value_changed():
	var v = get_value()
	set_base_string(v)
	
